//
//  HJStatusPictureView.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/26.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SDWebImage

private let HJStatusPictureViewCellIdentifier = "HJStatusPictureViewCellIdentifier"

class HJStatusPictureView: UICollectionView {
    private let layout = UICollectionViewFlowLayout()
    var pictureURLs: [NSURL]? {
        didSet {
            let viewSize = calcViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewSize)
            }
            reloadData()
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        registerClass(HJStatusPictureViewCell.self, forCellWithReuseIdentifier: HJStatusPictureViewCellIdentifier)
        dataSource = self
        self.backgroundColor = UIColor.clearColor()
    }
    
    private func calcViewSize() -> CGSize {
        layout.itemSize = CGSize(width: HJStatusPictureCellWH, height: HJStatusPictureCellWH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let count = pictureURLs?.count ?? 0
        if count == 0 {
            layout.itemSize = CGSizeZero
            return CGSizeZero
        }
        if count == 1 {
            // 一张图片默认大小
            var imageSize = CGSize(width: HJStatusPictureCellWH, height: HJStatusPictureCellWH)
            
            let imageURLString = pictureURLs![0].absoluteString
            // 获取图片有可能失败
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(imageURLString) {
                // 获取图片的大小显示
                imageSize = image.size
            }
            // 判断图片太小或太大
            if imageSize.width < 40 {
                imageSize.width = 40
            }else if imageSize.width > UIScreen.width * 0.5 {
                imageSize.width = UIScreen.width * 0.5
            }
            
            layout.itemSize = imageSize
            return imageSize
        }
        
        layout.minimumInteritemSpacing = HJStatusPictureViewCellMargin
        layout.minimumLineSpacing = HJStatusPictureViewCellMargin
        
        var column = HJStatusPictureMaxColumn
        if count == 2 || count == 4 {
            column = 2
        }
        let row = (count + column - 1) / column
        let width = CGFloat(column) * HJStatusPictureCellWH + (CGFloat(column) - 1) * HJStatusPictureViewCellMargin
        let height = CGFloat(row) * HJStatusPictureCellWH + (CGFloat(row) - 1) * HJStatusPictureViewCellMargin
        return CGSize(width: width, height: height)
    }
}

// MARK: - Custom StatusPictureViewCell
class HJStatusPictureViewCell: UICollectionViewCell {
    // MARK: - Attribute
    var imageURL: NSURL? {
        didSet {
            if let url = imageURL {
                // Load image
                backgroundImageView.sd_setImageWithURL(url)
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    
    private func prepareUI() {
        contentView.addSubview(backgroundImageView)
        
        backgroundImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        // 设置填充模式
        backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill
        // 裁剪
        backgroundImageView.clipsToBounds = true
    }
    
    // MARK: - Lazy load
    private lazy var backgroundImageView: UIImageView = UIImageView()
}

// MARK: - CollectionView source data
extension HJStatusPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HJStatusPictureViewCellIdentifier, forIndexPath: indexPath) as! HJStatusPictureViewCell
        cell.imageURL = pictureURLs?[indexPath.item]
        return cell
    }
}
